tl;dr, a safe way to program, for script, by adding these lines of code at the top of bash scripts for reliability.
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
set
A builtin that changes shell options. See manual.
set +e
disables option e
, set -e
enablesset -e
causes bash to exit if any command has a non-zero exit statusset -u
exits bash if a variable that does not exist is referencedset -o pipefail
makes exit code of pipelines that of a failing command instead of last command:
$ grep some-string /non/existent/file | sort
grep: /non/existent/file: No such file or directory # grep returns exit 2, sort has nothing to sort, returns exit 0
$ echo $?
0
The Internal Field Separator controls word splitting (or tokenization).
IFS='\n' # parse each line instead of each word
for name in ${names[@]}; do
echo $name
done
```